﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using Cashbook.Models;
using SQLite;
using Xamarin.Forms;

namespace Cashbook.Services
{
    public class CustomersDataAccess
    {
        readonly SQLiteAsyncConnection database;
        public ObservableCollection<Customer> Customers { get; set; }
		public CustomersDataAccess()
		{
			database = Database.GetDBConnection();

		}

		public async Task<ObservableCollection<Customer>> GetCustomersOC()
		{
            var collection = new ObservableCollection<Customer>();
			var items = await database.Table<Customer>().ToListAsync();
			foreach (var item in items)
			{
				collection.Add(item);
			}

			return collection;
		}

        public IEnumerable<Customer> GetCustomers()
		{
            return database.Table<Customer>().ToListAsync().Result;
		}

		public Task<List<Customer>> GetCustomersAsync()
		{
			return database.Table<Customer>().ToListAsync();
		}

		
		public Task<Customer> GetCustomerAsync(int id)
		{
			return database.Table<Customer>().Where(i => i.Id == id).FirstOrDefaultAsync();
		}

		public Task<int> SaveCustomerAsync(Customer item)
		{
           
			if (item.Id != 0)
			{
				return database.UpdateAsync(item);
			}
			else
			{
                return database.InsertAsync(item);
			}

			
		}
		

		public Task<int> DeleteCustomerAsync(Customer item)
		{
			return database.DeleteAsync(item);
		}
    }
}
